package com.jt.service.impl;

import com.jt.dao.MenuMapper;
import com.jt.pojo.Menu;
import com.jt.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class MenuServiceImpl implements MenuService {
    //注入方案1
    //@Autowired
    //private RedisTemplate redisTemplate;
    //@Autowired
    //private MenuMapper menuMapper;
    private static final Logger log=
            LoggerFactory.getLogger(MenuServiceImpl.class);
    //注入方案2
    private MenuMapper menuMapper;
    private ValueOperations valueOperations;

    public MenuServiceImpl(MenuMapper menuMapper,
                            RedisTemplate redisTemplate) {
        this.menuMapper = menuMapper;
        this.valueOperations = redisTemplate.opsForValue();
    }

    private static final String KEY_PREFIX="menu:";
    @Override
    public Menu selectById(Long id) {
        //1.从redis获取菜单信息,有则直接返回
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        Object obj = valueOperations.get(KEY_PREFIX + id);
        if(obj!=null){
            log.info("Data from Redis Cache");
            return (Menu)obj;
        }
        log.info("Data from MySQL");
        //2.从mysql数据库中查询菜单信息
        Menu menu=menuMapper.selectById(id);
        //3.将数据中查询到的菜单信息存储到redis
        valueOperations.set(KEY_PREFIX+id,
                menu,
                Duration.ofSeconds(60*60));
        //4.返回菜单对象
        return menu;
    }

    @Override
    public Menu insertMenu(Menu menu) {
        //1.保存到关系数据
        log.info("insert.before.menu={}",menu);
        menuMapper.insert(menu);
        log.info("insert.after.menu={}",menu);
        //2.将数据保存到缓存
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(KEY_PREFIX+menu.getId(),
                menu, Duration.ofSeconds(60*60));
        return menu;
    }

    @Override
    public Menu updateMenu(Menu menu) {
        //1.更新mysql数据
        menuMapper.updateById(menu);
        //2.更新缓存数据
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(KEY_PREFIX+menu.getId(),
                menu, Duration.ofSeconds(60*60));
        return menu;
    }
}
